package com.hhit.bigscreenbackmanage.service.impl.wlwsp;

import cn.hutool.http.HttpUtil;
import com.hhit.bigscreenbackmanage.common.BizConstants;
import com.hhit.bigscreenbackmanage.common.SignatureUtil;
import com.hhit.bigscreenbackmanage.enums.ReqEnum;
import com.hhit.bigscreenbackmanage.service.wlwsp.WlwspService;
import com.hhit.bigscreenbackmanage.vo.video.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hhit.bigscreenbackmanage.common.ComConst;
import com.hhit.bigscreenbackmanage.util.WlwspUtil;

import java.security.SecureRandom;


@Service
public class WlwspServiceImpl implements WlwspService {

    Logger logger = LoggerFactory.getLogger(WlwspServiceImpl.class);

//    @Autowired
//    private GisMapper gisMapper;

    @Value("${videoplatform.protocol}")
    private String videoPlatFormProtocol;

    @Value("${videoplatform.sysCode}")
    private String sysCode;

    @Value("${videoplatform.sysSecret}")
    private String sysSecret;

    @Value("${videoplatform.reqUrl}")
    private String reqUrl;


    /**
     * 获取视频播放地址URL信息
     *
     * @param deviceCodes 设备编码
     * @param deviceNames 设备名称
     * @param deviceIds 设备ID
     * @param wndIds 当前选中的窗口位置
     */
    public JSONObject getWlwspUrl(String deviceCodes, String deviceNames, String deviceIds,String wndIds){
        logger.info("getWlwspUrl==>");

//        Map result = new HashMap();
        JSONObject result= new JSONObject();
        JSONArray resultarr= new JSONArray();

        try {
            if(StringUtils.isNotEmpty(deviceCodes)){

                String [] codes = deviceCodes.split(",");
                String [] sbmcs = deviceNames.split(",");
                String [] sbids =deviceIds.split(",");

                int ii =0;
                for(int i=0;codes!=null&&codes.length>0&&i<codes.length;i++){
                    JSONObject resultObj = getWlwspdz(codes[i]);
                    JSONObject responseHead = resultObj.getJSONObject("responseHead");
//                System.out.println(i);
                    if(!"-1".equals(responseHead.getString("code"))){
                        JSONObject responseBody = resultObj.getJSONObject("responseBody");
                        String url = responseBody.getString("url");
                        if(ii<=9){//九格
                            JSONObject rst = new JSONObject();
                            rst.put("cameraIndexCode",sbids[i]);
                            rst.put("streamMode",0);
                            rst.put("cameraName",sbmcs[i]);
                            rst.put("url",url);
                            rst.put("deviceType",4);
                            rst.put("smallEagleEyeAbility",0);
                            rst.put("gpuMode",0);
                            if(StringUtils.isEmpty(wndIds)){
                                rst.put("wndId",++ii);
                            }else{
                                rst.put("wndId",Integer.parseInt(wndIds));
                            }
                            resultarr.add(rst);
                        }
                    }else{
                        JSONObject rst = new JSONObject();
                        rst.put("cameraIndexCode",sbids[i]);
                        rst.put("streamMode",0);
                        rst.put("cameraName",sbmcs[i]);
                        rst.put("url","rtsp://");
                        rst.put("deviceType",4);
                        rst.put("smallEagleEyeAbility",0);
                        rst.put("gpuMode",0);
                        rst.put("wndId",++ii);
                        resultarr.add(rst);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getWlwspUrl:获取视频播放地址URL信息失败："+e.getMessage());
        }
        result.put("list",resultarr);
        return result;
    }

    public JSONObject getWlwspdz(String code){
        String str ="";
        try {
            //参数
            JSONObject param=new JSONObject();
            param.put("deviceCode",code);
            param.put("protocol", "rtsp");
            //封装参数
            JSONObject paramJson= WlwspUtil.getWlwParamJson("/vdt-web/api/v1/previewURLs","GET_PREVIEWURLS",param);
            //接口返回
            str =  WlwspUtil.getDataClient(paramJson, ComConst.WLWAPI_SERVERPATH+"/vdt-web/api/v1/previewURLs");
            logger.info("getWlwspdz==>接口返回为:{}",str);
        }catch (Exception e) {
            logger.error("getWlwspdz==>请求视频平台异常:",e);
            str ="";
        }

        JSONObject resultObj = StringUtils.isNotEmpty(str)? JSONObject.parseObject(str):null;
        return resultObj;
    }

    @Override
    public int ptzControlling(String deviceCode, String action) throws Exception {
        logger.info("ptzControlling==>Call Begin,param[deviceCode:{},action:{}]",deviceCode,action);
        if (StringUtils.isBlank(deviceCode)
                || StringUtils.isBlank(action)){
            return -1;
        }
        // 组装请求头信息
        long timestamp = System.currentTimeMillis();
        int nonce = new SecureRandom().nextInt(100000);
        String signature = SignatureUtil.encryptSHA("POST", ReqEnum.PTZ_CONTROLLING.getReqUrl(),sysCode,timestamp,nonce,sysSecret);
        RequestHead requestHead = new RequestHead();
        requestHead.setMethod(ReqEnum.PTZ_CONTROLLING.getMothod());
        requestHead.setNonce(nonce);
        requestHead.setSignature(signature);
        requestHead.setSystemCode(sysCode);
        requestHead.setTimestamp(timestamp);

        // 组装请求体信息
        PtzControllingRequestBody ptzControllingRequestBody = new PtzControllingRequestBody();
        ptzControllingRequestBody.setDeviceCode(deviceCode);
        ptzControllingRequestBody.setAction(action);

        JsonRootBean jsonRootBean = new JsonRootBean();
        jsonRootBean.setRequestHead(requestHead);
        jsonRootBean.setRequestBody(ptzControllingRequestBody);
        // http请求统一视频平台，进行设备云台控制
        String paramJson = JSONObject.toJSONString(jsonRootBean);
        logger.info("ptzControlling-->sendHttpReq Begin,paramJson:{}",paramJson);
        String result = HttpUtil.post(reqUrl+"/"+ReqEnum.PTZ_CONTROLLING.getReqUrl(),paramJson);
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        logger.info("ptzControlling-->sendHttpReq End,resultJson[resultJson:{}]",resultJson);
        if (null != resultJson){
            JSONObject responseHeadJson = JSONObject.parseObject(resultJson.getString("responseHead"));
            String code = responseHeadJson.getString("code");
            return Integer.parseInt(code);
        }else{
            logger.info("ptzControlling==>resultJson为空");
            throw new Exception("ptzControlling-->请求统一视频平台返回结果为空");
        }
    }

    @Override
    public String getDevicePreviewurls(String deviceCode,String protocol) throws Exception{
        if (StringUtils.isBlank(protocol)){
            protocol = videoPlatFormProtocol;
        }
        // 组装请求头信息
        long timestamp = System.currentTimeMillis();
        int nonce = new SecureRandom().nextInt(100000);
        String signature = SignatureUtil.encryptSHA("POST", ReqEnum.GET_PREVIEWURLS.getReqUrl(),sysCode,timestamp,nonce,sysSecret);
        RequestHead requestHead = new RequestHead();
        requestHead.setMethod(ReqEnum.GET_PREVIEWURLS.getMothod());
        requestHead.setNonce(nonce);
        requestHead.setSignature(signature);
        requestHead.setSystemCode(sysCode);
        requestHead.setTimestamp(timestamp);

        // 组装请求体信息
        PreviewurlsRequestBody previewurlsRequestBody = new PreviewurlsRequestBody();
        previewurlsRequestBody.setDeviceCode(deviceCode);
        previewurlsRequestBody.setProtocol(protocol);

        JsonRootBean jsonRootBean = new JsonRootBean();
        jsonRootBean.setRequestHead(requestHead);
        jsonRootBean.setRequestBody(previewurlsRequestBody);
        // http请求统一视频平台，获取视频播放url
        String paramJson = JSONObject.toJSONString(jsonRootBean);

        String result = HttpUtil.post(reqUrl+"/"+ReqEnum.GET_PREVIEWURLS.getReqUrl(),paramJson);
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        logger.info("getDevicePreviewurls-->sendHttpReq End,resultJson[resultJson:{}]",resultJson);
        if (null != resultJson){
            JSONObject responseHeadJson = JSONObject.parseObject(resultJson.getString("responseHead"));
            String code = responseHeadJson.getString("code");
            if (Integer.parseInt(code) == BizConstants.AI_VP_CODE_SUCCESS.intValue()){
                JSONObject responseBodyJson = JSONObject.parseObject(resultJson.getString("responseBody"));
                String url = responseBodyJson.getString("url");
                return url;
            }else{
                logger.info("getDevicePreviewurls==>responseHeadJson不为空且Code不为0");
                throw new Exception("统一视频平台请求失败");
            }
        }else{
            logger.info("getDevicePreviewurls==>resultJson为空");
            throw new Exception("getDevicePreviewurls-->请求统一视频平台返回结果为空");
        }
    }

    @Override
    public int getOnlineStatus(String deviceCode) throws Exception {
        if (StringUtils.isBlank(deviceCode)){
            return -1;
        }
        // 组装请求头信息
        long timestamp = System.currentTimeMillis();
        int nonce = new SecureRandom().nextInt(100000);
        String signature = SignatureUtil.encryptSHA("POST", ReqEnum.GET_ONLINE_STATUS.getReqUrl(),sysCode,timestamp,nonce,sysSecret);
        RequestHead requestHead = new RequestHead();
        requestHead.setMethod(ReqEnum.GET_ONLINE_STATUS.getMothod());
        requestHead.setNonce(nonce);
        requestHead.setSignature(signature);
        requestHead.setSystemCode(sysCode);
        requestHead.setTimestamp(timestamp);

        RequestBody requestBody = new RequestBody();
        requestBody.setDeviceCode(deviceCode);

        JsonRootBean jsonRootBean = new JsonRootBean();
        jsonRootBean.setRequestHead(requestHead);
        jsonRootBean.setRequestBody(requestBody);
        // http请求统一视频平台，进行设备云台控制
        String paramJson = JSONObject.toJSONString(jsonRootBean);
        logger.info("getOnlineStatus-->sendHttpReq Begin,paramJson:{}",paramJson);
        String result = HttpUtil.post(reqUrl+"/"+ReqEnum.GET_ONLINE_STATUS.getReqUrl(),paramJson);
        JSONObject resultJson = JSONObject.parseObject(result.trim());
        logger.info("getOnlineStatus-->sendHttpReq End,resultJson[resultJson:{}]",resultJson);
        if (null != resultJson){
            JSONObject responseHeadJson = JSONObject.parseObject(resultJson.getString("responseHead"));
            String code = responseHeadJson.getString("code");
            if (Integer.parseInt(code) == 0){
                // 获取设备状态
                JSONObject responseBodyJson = JSONObject.parseObject(resultJson.getString("responseBody"));
                return  Integer.parseInt(responseBodyJson.getString("onlineStatus"));
            }else if (Integer.parseInt(code) == -1){
                String responseBodyStr = resultJson.getString("responseBody");
                if (responseBodyStr.contains("使用权限")){
                    return 3;
                }
            }
        }else{
            logger.info("getOnlineStatus==>resultJson为空");
            throw new Exception("getOnlineStatus-->请求统一视频平台返回结果为空");
        }
        return 2;
    }
}
